<template>
  <div class="relative top-[56px] left-0 tree-container">
    <el-input
      placeholder="输入关键字进行过滤"
      v-model="filterText">
    </el-input>

    <div class="tree-scroll h-[100vh] overflow-y-auto">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        class="filter-tree"
        :data="treeData"
        :props="defaultProps"
        :expanded-keys="expandedKeys"
        default-expand-all
        :filter-node-method="filterNode"
        :render-content="renderContent"
        @node-expand="handleNodeExpand">
      </el-tree>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits, onMounted, toRef, onUnmounted } from 'vue'
import { ElTree } from 'element-plus'

// 过滤有关的代码
interface Tree {
  [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  label: 'label',
}

watch(filterText, (val:any) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

// 定义传递的 props
const props = defineProps({
  elementNames: {
    type: Array,
    default: () => []
  },
  ruleData: {
    type: Array,
    default: () => []
  },
  assignedCounts: {
    type: Object,
    default: () => ({}),
  }
});

const emit = defineEmits(['toggleRegion'])

const ruleData = toRef(props, 'ruleData');
const elementNames = toRef(props, 'elementNames');
const assignedCounts = toRef(props, 'assignedCounts');
const treeData = ref([]); // 初始化为空数组
const sessionId = ref<string | null>(null); // 存储 sessionId

// 登录接口获取动态 sessionId
const login = await fetch(`http://47.100.168.221:9999/gps-web/api/login.jsp?password=c65c636e668a7872e393058856be20f5&userId=SHJC_PDGJ&loginType=user`);
const loginData = await login.json();
sessionId.value = loginData.sessionId;


const selectionStatus = ref<{ [key: string]: boolean }>({}); // 保存每个区域的选择状态
const expandedKeys = ref<string[]>([]); // 保存展开状态：

// 处理树节点展开事件
const handleNodeExpand = (node: any, expandedKeys: string[]) => {
  // 保存展开的节点
  expandedKeys.value = expandedKeys;
}

// 获取每个区域的在线人数
const fetchOnlineCountForRegion = async (regionId: string) => {
  try {
    const response = await fetch(`http://47.100.168.221:9999/gps-web/api/get_region_car.jsp?sessionId=${sessionId.value}&regionIds=${regionId}`);
    const data = await response.json();
    return data.list && data.list.length > 0 ? data.list[0].carList.length : 0;
  } catch (error) {
    console.error("Error fetching online count for region:", error);
    return 0;
  }
}

const updateTreeData = async () => {
  const updatedTreeData = await Promise.all(elementNames.value.map(async (item: any) => {
    const isEnabled = ruleData.value.includes(item.id);
    const onlineCount = await fetchOnlineCountForRegion(item.id);
    const assignedCount = assignedCounts.value[item.id] || 0;

    // 保留之前的选择状态，如果没有则默认选中
    const isSelected = selectionStatus.value[item.id] ?? true;

    return {
      id: item.id,
      label: item.name,
      selected: isSelected,
      name: item.name, // 保存原始名称
      children: [
        { label: `在线人数：${onlineCount}` },
        { label: `分配人数：${assignedCount}` },
        { label: `在线状态：${isEnabled ? '\u00A0\u00A0 已启用' : '\u00A0\u00A0 未启用'}` }
      ]
    }
  }));

  // 更新树数据
  if (JSON.stringify(updatedTreeData) !== JSON.stringify(treeData.value)) {
    treeData.value = updatedTreeData;
  }
}

let intervalId: NodeJS.Timeout;

onMounted(() => {
  updateTreeData(); // 初始化数据
  intervalId = setInterval(updateTreeData, 2000); // 每2秒更新一次数据
})

onUnmounted(() => {
  clearInterval(intervalId); // 清理定时器
})

// 单选框控制围栏显示与否的功能
const toggleSelection = (data: any) => {
  data.selected = !data.selected
  selectionStatus.value[data.id] = data.selected; // 更新选择状态
  emit('toggleRegion', data.id, data.selected)
}

// 一级标题显示单选框和对应位置显示徽标的功能
const renderContent = (h: any, { node, data }) => {
  const showCheckbox = data.name === node.label
  const isOnlineStatus = node.label.includes('在线状态') // 判断是否是在线状态行
  const isEnabled = node.label.includes('已启用') // 判断是否为已启用状态

  return h('span', [
    // 如果需要显示复选框
    showCheckbox ? h('input', {
      class:"dx-input",
      type: 'checkbox',
      checked: data.selected, // 复选框是否被选中
      onClick: (event: any) => event.stopPropagation(), // 阻止事件冒泡，避免点击复选框时触发其他事件
      onChange: () => toggleSelection(data),  // 复选框状态改变时调用 toggleSelection 方法
      style: { marginRight: '6px' } // 设置复选框右边距
    }) : null,
    
    isOnlineStatus ? h('span', { class: 'status-item' }, [
      h('span', node.label), // 在线状态文本
      h('span', { class: 'status-dot', style: { backgroundColor: isEnabled ? 'green' : 'blue' } }) // 根据是否启用设置圆点颜色
    ]) : h('span', node.label) // 其他行只显示节点标签
  ])
}
</script>

<style>
.tree-container {
  width: 17vw;
  padding: 15px;
  border: 1px solid #dcdcdc;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.el-tree {
  font-size: 14px;
  color: #666;
}

.el-input {
  margin-bottom: 15px;
}

.tree-node {
  display: flex;
  align-items: center;
}

.main-node {
  font-weight: bold;
  font-size: 14px;
}

.sub-node {
  font-size: 14px;
  color: #333;
}

.dx-input{
  margin-left: -2px;
}

.el-icon{
  margin-left: -9px;
}

.status-item {
  display: flex;
  align-items: center;
}

.status-text {
  display: flex;
  align-items: center;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-left: -54px; /* 让圆点来到文字前面 */
  margin-top: 2px; 
}
.el-tree-node__content {
  word-wrap: break-word; /* 处理过长的文字内容换行 */
  word-break: break-all; /* 处理过长的文字内容换行 */
}
</style>